//
//  ListViewController.m
//  HZHome
//
//  Created by SunShine on 13-9-21.
//  Copyright (c) 2013年 xzysun. All rights reserved.
//  列表公共方法实现
//

#import "ListViewController.h"
#import "MapViewController.h"
#import "StreetGuidDetailController.h"
#import "StreetGuideDetailWebViewController.h"
#import "CommonGuidDetailController.h"
#import "EnterpriseGuidDetailController.h"
#import "MyConcernService.h"
#import "MineQueryDetailInfoViewController.h"
#import "MYGuideCommonService.h"
#import "MapNavigationViewController.h"
#import "CommonMineQueryItem.h"

@interface ListViewController () <SearchViewDelegate,SegmentViewDelegate,CLLocationManagerDelegate>
@property (strong, nonatomic) CustomPullToRefresh *ptr;
@property (strong, nonatomic) NSString *phoneToCall;
@property (assign, nonatomic) BOOL fastSearch;
@property (assign, nonatomic) BOOL fastSearchTarget;
@property (assign, nonatomic) NSInteger fastSearchType;
@property (strong, nonatomic) SegmentView *segmentView;
@property (strong, nonatomic) SearchView *searchView;

@property (assign, nonatomic) BOOL isMyConcern;
@property (strong, nonatomic) NSString *myGudieServe;//列表数据处理服务类
@property (strong, nonatomic) NSString *myGudieCell; //列表单元格处理类

@property (strong, nonatomic) NSString *keyStr;//模块名称

@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) MyAnnotation *annotation;

@end

@implementation ListViewController
@synthesize isMyConcern;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.tipLabel.hidden = YES;
    [self configVC];
}

static BOOL onceReturn;//用于标记一次性返回
-(void)backMethod{
    //重写返回上级的方法，在返回前先清理下内存
    _dataService.dataList = nil;
    self.dataService = nil;
    onceReturn = YES;
    self.locationManager.delegate = nil;
    self.locationManager = nil;
    [super backMethod];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView setBackgroundView:nil];
    [self.tableView setBackgroundColor:[UIColor clearColor]];
    [self.tableView reloadData];
    self.navigationController.navigationBar.hidden = NO;
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)containsString:(NSString *)key aString:(NSString *)aString{
    if ([key isEqualToString:aString]) {
        return YES;
    }
	NSRange range = [[key lowercaseString] rangeOfString:[aString lowercaseString]];
	return range.location != NSNotFound;
}

- (BOOL)equalString:(NSString *)key aString:(NSString *)aString{
    if ([key isEqualToString:aString]) {
        return YES;
    }
   return NO;
}

#pragma mark - Config
-(void)configVC{
    _tempConfig =[NSMutableDictionary dictionaryWithDictionary:_config];
    _keyStr = [_config objectForKey:@"key"];
    if (_keyStr) {
        //communityCategory:1表示民意征集，2表示我要投票
        if ([_keyStr isEqualToString:@"民意征集"]) {
            [_tempConfig setObject:@"1" forKey:@"communityCategory"];
        }else if([_keyStr isEqualToString:@"我要投票"]){
            [_tempConfig setObject:@"2" forKey:@"communityCategory"];
        }
    }
    BOOL isGuide = [[_config objectForKey:@"Guide"] boolValue];
    int guideIndex = [[_config objectForKey:@"GuideIndex"] intValue];
    isMyConcern = [[_config objectForKey:@"MyConcern"] boolValue];
    self.myGudieServe = [_config objectForKey:@"myGudieServe"];
    self.myGudieCell = [_config objectForKey:@"myGudieCell"];

    //检查是否传入快速搜索的关键字
    NSString *fastSearchKey = [_config objectForKey:@"fastSearchKey"];
    self.fastSearchType = [(NSNumber *)[_config objectForKey:@"fastSearchType"] integerValue];
    //检查是否有传入的dataItem
    id dataItem = [_config objectForKey:@"dataItem"];
    //读取配置文件
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"ListPages" ofType:@"plist"];
    NSDictionary *listPageConfigs = [[NSDictionary alloc]initWithContentsOfFile:plistPath];
    BOOL isCom = NO;
    for (NSString *keyString in listPageConfigs) {
        if ([self equalString:keyString aString:_keyStr]) {
            isCom = YES;
            continue;
        }
    }
    if (!isCom && !isMyConcern) {
        for (NSString *keyString in listPageConfigs) {
            NSMutableString* strDeviceToken = [[NSMutableString alloc] initWithFormat:@"%@", keyString];
            if ([self containsString:strDeviceToken aString:_keyStr]) {
                _keyStr = strDeviceToken;
                continue;
            }
        }
    }
    self.config  = [listPageConfigs objectForKey:_keyStr];
    
    //产生数据服务对象
    Class tempClass = nil;
    if (isMyConcern) {
        tempClass =  NSClassFromString(self.myGudieServe);
    } else {
         tempClass=  NSClassFromString([_config objectForKey:@"serviceName"]);
    }
    self.dataService = [[tempClass alloc]init];
    self.dataService.delegate = self;
    self.dataService.dataItem = dataItem;
    self.dataService.paramDic = _tempConfig;
  
    //显示标题
    self.title = [_config objectForKey:@"title"];
    if ( [@"社区党组织-支部列表" isEqualToString:[_config objectForKey:@"title"]] ) {
        self.title = [_tempConfig objectForKey:@"title"];
    }
    //右上角按钮的显示
    bool showRightBt = [(NSNumber*)[_config valueForKey:@"rightBt"] boolValue];
    if (showRightBt) {
        NSString *rightBtName = [_config objectForKey:@"rightBtName"];
        self.navigationItem.rightBarButtonItem = rightNavBtnWithImgName(rightBtName, self, @selector(rightBtAction));
    }
    int segBarHeight = 0;
    int tipsHeight = 0;
    //控制segBar
    NSArray *tmpeArray = nil;
    if (isGuide) {
        tmpeArray = [_dataService getSegmentsTitles:guideIndex];
        if (guideIndex == 1) {
            [self.dataService selectSegmentBarAtIndex:1];
        }
    } else{
        tmpeArray = [_dataService getSegmentsTitles];

    }
    NSMutableArray *array = [[NSMutableArray alloc] init];
    for (NSString *stirng in tmpeArray) {
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        [dict setObject:stirng forKey:@"image"];
        [dict setObject:[NSString stringWithFormat:@"%@_选中",stirng] forKey:@"light"];

        [array addObject:dict];
    }
    bool showSegmentBar = [(NSNumber*)[_config valueForKey:@"segmentBar"] boolValue];
    if (self.segmentView == nil) {
        self.segmentView = [[SegmentView alloc] initWithFrame:CGRectMake(0, 0, 320, 29)];
    }
    if (showSegmentBar) {
        segBarHeight = 44;
        [self.segmentView setFrame:CGRectMake(0, 0, 320, 29)];
        self.segmentView.delegate = self;
        
    } else {
        [self.segmentView setFrame:CGRectZero];
    }
    
    [self.segmentView initView:array];
    if (self.segmentView == nil) {
    }
    [self.view addSubview:self.segmentView];

    //控制搜索栏
    if (self.searchView == nil) {
        self.searchView = [SearchView initView];
        [self.searchView setFrame:CGRectMake(0, 44, 320, 43)];
        [self.view addSubview:self.searchView];
    }

    
    bool showSearchBar = [(NSNumber*)[_config valueForKey:@"searchBar"] boolValue];
    if (showSearchBar) {
        self.searchView.hidden = NO;
        self.searchView.textField.placeholder = [NSString stringWithFormat:@"请输入%@名称",_keyStr];
        self.searchView.delegate = self;
        self.searchView.textField.inputAccessoryView = [self getInputAccessoryView];
    } else {
        self.searchView.hidden = YES;
    }
    if (self.searchText && self.searchView) {
        self.searchView.textField.text = self.searchText;
        self.searchView.searchText = self.searchText;
    }
    
    BOOL fastSearchFlag = [(NSNumber *)[_config valueForKey:@"fastSearch"] boolValue];
    if (fastSearchFlag) {
        NSLog(@"这个页面包含快速搜索入口");
        self.fastSearch = true;
    }
    //控制底部Tips视图
    BOOL tipsFlag = [(NSNumber *)[_config valueForKey:@"tips"] boolValue];
    if (tipsFlag) {
        tipsHeight = 40;
        self.tipsView.hidden = NO;
        self.tipsView.text = [_dataService getButtomTips];
    } else {
        self.tipsView.hidden = YES;
    }

    CGRect searchFrame = self.searchView.frame;
    CGRect segmentFrame = self.segmentView.frame;

    CGRect tableFrame = _tableView.frame;
    int stautsBarHeight = 0;
    if (self.navigationController.navigationBarHidden) {
        stautsBarHeight = 20;
        self.title = @"查找";
    }
    if (!showSegmentBar && showSearchBar) {
        searchFrame.origin.y = 0 + stautsBarHeight;
        tableFrame.origin.y = 43 + stautsBarHeight;
        tableFrame.size.height +=43 + stautsBarHeight;
    }else  if (showSegmentBar && showSegmentBar) {
        segmentFrame.origin.y = 0 + stautsBarHeight;
        searchFrame.origin.y = 29 + stautsBarHeight;
        tableFrame.origin.y = 73 + stautsBarHeight;
        tableFrame.size.height += 29 + stautsBarHeight;
    }  else if (!showSearchBar){
            tableFrame.origin.y =  stautsBarHeight ;
            tableFrame.size.height +=43 + stautsBarHeight;
    }
   
    
    if (!tipsFlag) {
        tableFrame.size.height += 40.0;
    }

    self.searchView.frame = searchFrame;
    self.segmentView.frame = segmentFrame;
    _tableView.frame = tableFrame;
    if (self.config == nil) {
        searchFrame.origin.y = 0;
        self.tipLabel.hidden = NO;
        self.searchView.hidden = NO;
        [self.searchView setFrame:searchFrame];
        self.searchView.delegate = self;
        self.title = @"查找";
    }
    //开启下拉刷新
    self.ptr = [[CustomPullToRefresh alloc]initWithScrollView:self.tableView delegate:self];
    //检查传入的快速搜索
    if (fastSearchKey) {
        NSLog(@"检测到传入的快速搜索参数%@", fastSearchKey);
        self.fastSearchTarget = YES;
        self.searchView.textField.text = fastSearchKey;
        self.dataService.fastSearchType = self.fastSearchType;
        [self startLoadingView];
        [self.dataService loadDataWithKey:fastSearchKey];
    } else {
        //开始读取数据
    [self startLoadingView];
    [self.dataService loadDataWithKey:nil];
    }
}

-(void) rightBtAction
{
    NSString *rightBtTarget = [_config objectForKey:@"rightBtTarget"];
    //进入下一级页面
    Class tempClass =  NSClassFromString(rightBtTarget);
    if (!tempClass) {
        NSLog(@"target%@类型不正确",rightBtTarget);
        return;
    }
    ConfigableViewController *vc = [[tempClass alloc]initWithNibName:rightBtTarget bundle:nil];
    if (self.dataService.dataItem) {
        //如果有dataItem，传入右键的目标里
        vc.config = [NSDictionary dictionaryWithObjectsAndKeys:self.dataService.dataItem, @"dataItem", nil];
    }
     vc.tempConfig = _tempConfig;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)phoneButtonAction:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    NSObject *item = [self.dataService.dataList objectAtIndex:btn.tag];
    NSString* phone = [item valueForKey:@"phone"];
    [self isCallPhone:phone];
}

-(void)mapButtonAction:(id)sender{
    UIButton *btn = (UIButton *)sender;
    NSObject *item = [self.dataService.dataList objectAtIndex:btn.tag];
    NSString* point = [item valueForKey:@"point"];
    NSLog(@"点击了地图按钮%@",point);
    //go into map view
    
    double longitude = [point substringToIndex:[point rangeOfString:@"|"].location].floatValue;
    double latitude = [point substringFromIndex:[point rangeOfString:@"|"].location + 1].floatValue;
    CLLocationCoordinate2D centerCoord = CLLocationCoordinate2DMake(latitude, longitude);

    self.annotation = nil;
   self.annotation = [[MyAnnotation alloc] init];
    self.annotation.coordinate = centerCoord;
    self.annotation.title = ((CommonMineQueryItem *)item).title;
    self.annotation.subtitle = ((CommonMineQueryItem *)item).address;
    self.annotation.strtel = ((CommonMineQueryItem *)item).phone;

    
    if (self.locationManager == nil) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = 1000.0f;
    }

    if ([CLLocationManager locationServicesEnabled]) {
        [self.locationManager startUpdatingLocation];
    }

    
}

#pragma mark - CLLocationManagerDelegate
// 地理位置发生改变时触
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    [self.locationManager stopUpdatingLocation];

    if (locations.count > 0) {
        CLLocation *newLocation = (CLLocation *)[locations objectAtIndex:0];
        MapNavigationViewController *vc = [MapNavigationViewController new];
        vc.annotation = self.annotation;
        vc.location = newLocation;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    
}

//社区自治-党的建设-社区党组织-支部-列表电话事件
- (void)partyPhoneButtonAction:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    NSObject *item = [self.dataService.dataList objectAtIndex:btn.tag];
    NSString* phone = [item valueForKey:@"partyMobile"];
    [self isCallPhone:phone];
}


-(void)isCallPhone:(NSString*)phone {
    if ([phone rangeOfString:@","].location != NSNotFound) {
        NSLog(@"准备截断电话号码%@",phone);
        phone = [phone substringToIndex:[phone rangeOfString:@","].location];
    }
    NSLog(@"点击了电话按钮%@",phone);
    self.phoneToCall = phone;
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString  stringWithFormat:@"您是否需要拨打电话%@",phone] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = PHONE_ALERT_TAG;
    [alert show];
}



//指南按钮点击事件
-(void)guidButtonAction:(id)sender{
    UIButton *guidButton = (UIButton *)sender;
     StreetGuidDetailController *guidVC = [[StreetGuidDetailController alloc]initWithNibName:@"StreetGuidDetailController" bundle:nil];
    StreetWorkGuideEntity *entity=[self.dataService.dataList objectAtIndex:guidButton.tag];
    guidVC.item=entity;
     [self.navigationController pushViewController:guidVC animated:YES];
}
//企业办事指南查询
-(void)guidEnterpriseButtonAction:(id)sender{
    UIButton *guidButton = (UIButton *)sender;
    CommonWorkGuideEntity *entity=[self.dataService.dataList objectAtIndex:guidButton.tag];
    EnterpriseGuidDetailController *guidVC = [[EnterpriseGuidDetailController alloc]initWithNibName:@"EnterpriseGuidDetailController" bundle:nil];
    guidVC.item=entity;
    [self.navigationController pushViewController:guidVC animated:YES];
    
}
//居民和企业办事指南按钮点击事件
-(void)guidCommonButtonAction:(id)sender{
    UIButton *guidButton = (UIButton *)sender;

    id item = [_dataService.dataList objectAtIndex:guidButton.tag];
    if ([item isKindOfClass:[StreetWorkGuideEntity class]]) {
        //按街道筛选
        StreetGuidDetailController *guidVC = [[StreetGuidDetailController alloc]initWithNibName:@"StreetGuidDetailController" bundle:nil];
        guidVC.item= item;
        [self.navigationController pushViewController:guidVC animated:YES];
    } else if ([item isKindOfClass:[StreetWorkGuideOrgEntity class]]) {
        //按部门筛选
        StreetGuideDetailWebViewController *webVC = [[StreetGuideDetailWebViewController alloc] initWithNibName:@"StreetGuideDetailWebViewController" bundle:nil];
        webVC.item = item;
        [self.navigationController pushViewController:webVC animated:YES];
    }
}
#pragma mark - Alert View Delegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == PHONE_ALERT_TAG) {
        if (buttonIndex == 1) {
           
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",_phoneToCall]]];
        }
    }
}

#pragma mark - Table
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return _dataService.dataList?[_dataService.dataList count]:0;
    } else {
        return 0;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self.dataService heightForCellAtRow:indexPath];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellName = [_config objectForKey:@"cellClassName"];

    if (isMyConcern) {
        cellName = self.myGudieCell;
    }
    Class cellClass =  NSClassFromString(cellName);
    if (!cellClass) {
        NSLog(@"cellClass%@类型不正确",cellName);
        return nil;
    }
    NSLog(@"cellName = %@",cellName);
    static NSString *cellIdentifier = @"ListViewCell";
    UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
    cell = [[[NSBundle mainBundle]loadNibNamed:cellName owner:self options:nil]objectAtIndex:0];
    }
    [cell setBackgroundColor:[UIColor clearColor]];
    //调用service对cell赋值
    [_dataService configCell:cell atIndex:indexPath];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dic = [self.dataService getTargetConfigForCellAtIndex:indexPath];
    NSLog(@"dic  -  %@",dic);
    if (!dic) {
        NSLog(@"未能获取到配置,无法进入下一页面");
        return;
    }
    
    NSLog(@"nameee = %@",[_config objectForKey:@"targetClassName"]);
    if (isMyConcern) {
        if ([self.myGudieServe isEqualToString:@"MyConcernService"]) {
            MineQueryDetailInfoViewController *vc = [[MineQueryDetailInfoViewController alloc] init];
            vc.config = dic;
            [self.navigationController pushViewController:vc animated:YES];
        } else {
            StreetWorkGuideEntity *item = [_dataService.dataList objectAtIndex:indexPath.row];
            NSLog(@"item type = %@",item.dataType);
            NSLog(@"item id = %@",item.Id);
            if ([item.dataType isEqualToString:@"SERVICE_ITEM"]) {
                StreetGuidDetailController *vc = [[StreetGuidDetailController alloc] init];
                vc.config = dic;
                [self.navigationController pushViewController:vc animated:YES];
            } else {
                EnterpriseGuidDetailController *vc = [[EnterpriseGuidDetailController alloc]initWithNibName:@"EnterpriseGuidDetailController" bundle:nil];
                vc.config = dic;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
        return;
    }
    ConfigableViewController *vc = [_dataService getCellTargetViewControllerForName:[_config objectForKey:@"targetClassName"]];
    vc.config = dic;
    vc.tempConfig = _tempConfig;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - Segment Delegate
- (void)didSelectSegmentAtIndex:(int)index{
    self.searchView.textField.text = @"";
    [self.dataService selectSegmentBarAtIndex:index];
    [self startLoadingView];
}
-(void)segmentValueChanged{
    NSInteger selected = self.segmentedController.selectedSegmentIndex;
    NSLog(@"selected segment index:%d",selected);
    self.searchView.textField.text = @"";
    [self.dataService selectSegmentBarAtIndex:selected];
    [self startLoadingView];
}

#pragma mark - Search Bar Delegate
- (void)didSearchText:(NSString *)text{
    if (self.config != nil) {
        NSLog(@"search button clicked with input:%@",text);
        //    [searchBar resignFirstResponder];
        if (text.length == 0) {
            //如果没输入内容并且点击完成，则重新刷新列表
            [self startLoadingView];
            [self.dataService loadDataWithKey:nil];
        } else if (!_fastSearch){
            //搜索框不为空，且不是快速搜索
            [self startLoadingView];
            [self.dataService loadDataWithKey:text];
        } else {
            //快速搜索
            ConfigableViewController *vc = [_dataService getCellTargetViewControllerForName:[_config objectForKey:@"targetClassName"]];
            bool showSegmentBar = [(NSNumber*)[_config valueForKey:@"segmentBar"] boolValue];
            if (showSegmentBar) {
                //如果快速搜索时有seg则传入seg的选择状态
                vc.config = [NSDictionary dictionaryWithObjectsAndKeys:[_config objectForKey:@"fastSearchTarget"], @"key", text, @"fastSearchKey",[NSNumber numberWithInteger:self.segmentView.segmentIndex], @"fastSearchType", nil];
            } else {
                vc.config = [NSDictionary dictionaryWithObjectsAndKeys:[_config objectForKey:@"fastSearchTarget"], @"key", text, @"fastSearchKey", nil];
            }
            [self.navigationController pushViewController:vc animated:YES];
        }
        self.searchView.textField.text = text;
    } else {
        
        self.tipLabel.hidden = YES;
        [self startLoadingView];
        [self.dataService loadDataWithKey:text];
        self.searchView.textField.text = text;
    }
}


-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"search button clicked with input:%@",searchBar.text);
    [searchBar resignFirstResponder];
    if (searchBar.text.length == 0) {
        //如果没输入内容并且点击完成，则重新刷新列表
        [self startLoadingView];
        [self.dataService loadDataWithKey:nil];
    } else if (!_fastSearch){
        //搜索框不为空，且不是快速搜索
        [self startLoadingView];
        [self.dataService loadDataWithKey:searchBar.text];
    } else {
        //快速搜索
        ConfigableViewController *vc = [_dataService getCellTargetViewControllerForName:[_config objectForKey:@"targetClassName"]];
        bool showSegmentBar = [(NSNumber*)[_config valueForKey:@"segmentBar"] boolValue];
        if (showSegmentBar) {
            //如果快速搜索时有seg则传入seg的选择状态
            vc.config = [NSDictionary dictionaryWithObjectsAndKeys:[_config objectForKey:@"fastSearchTarget"], @"key", searchBar.text, @"fastSearchKey",[NSNumber numberWithInteger:_segmentedController.selectedSegmentIndex], @"fastSearchType", nil];
        } else {
            vc.config = [NSDictionary dictionaryWithObjectsAndKeys:[_config objectForKey:@"fastSearchTarget"], @"key", searchBar.text, @"fastSearchKey", nil];
        }
        [self.navigationController pushViewController:vc animated:YES];
    }
}
- (void)searchBarTextDidEnd:(NSString *)text{
    NSLog(@"search button clicked with input:%@",text);
    if (self.config != nil) {
        if (text.length == 0) {
            //如果没输入内容并且点击完成，则重新刷新列表
            [self startLoadingView];
            [self.dataService loadDataWithKey:nil];
        } else if (!_fastSearch){
            //搜索框不为空，且不是快速搜索
            [self startLoadingView];
            [self.dataService loadDataWithKey:text];
        } else {
            //快速搜索
            ConfigableViewController *vc = [_dataService getCellTargetViewControllerForName:[_config objectForKey:@"targetClassName"]];
            bool showSegmentBar = [(NSNumber*)[_config valueForKey:@"segmentBar"] boolValue];
            if (showSegmentBar) {
                //如果快速搜索时有seg则传入seg的选择状态
                vc.config = [NSDictionary dictionaryWithObjectsAndKeys:[_config objectForKey:@"fastSearchTarget"], @"key", text, @"fastSearchKey",[NSNumber numberWithInteger:_segmentedController.selectedSegmentIndex], @"fastSearchType", nil];
            } else {
                vc.config = [NSDictionary dictionaryWithObjectsAndKeys:[_config objectForKey:@"fastSearchTarget"], @"key", text, @"fastSearchKey", nil];
            }
            [self.navigationController pushViewController:vc animated:YES];
        }

    }
}

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    if (self.config != nil) {
        
    }
    NSLog(@"search bar end edit with input %@",searchBar.text);
    if (self.fastSearchTarget && searchBar.text.length == 0) {
        //如果是快速搜索的目标，清空搜索的时候返回上一页
//        [self.navigationController popViewControllerAnimated:YES];
        if (!onceReturn) {//因为键盘的退出机制会导致这里调用两次pop,所以这里做一个控制防止多次pop引起异常崩溃
            onceReturn = YES;
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}
#pragma mark - Data Service
-(void)loadDataFinished{

    if (isMyConcern && [_dataService.dataList count] > 0) {
        self.tipLabel.hidden = YES;
        CGRect frame = self.tableView.frame;
        frame.origin.y = 43;
        frame.size.height = 460;
        [self.tableView setFrame:frame];
    }
    [self stopLoadingView];
    [self.ptr endRefresh];
    [self.tableView reloadData];
}

-(void)loadDataFaild:(NSString *)msg{
    [self stopLoadingView];
    [self.ptr endRefresh];
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"错误" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

-(void)setEnableToLoadMore:(BOOL)enable{
    self.ptr.enablePullToBottom = enable;
}

#pragma mark - PullToRefresh Method
//捕获到拉动事件
-(void)customPullToRefreshShouldRefresh:(CustomPullToRefresh *)ptr withDirection:(MSRefreshDirection)direction{
    NSLog(@"捕获到拉动事件");
    if (direction == MSRefreshDirectionTop) {
        if (self.searchView.textField.text == 0 || _fastSearch) {
            [self.dataService loadDataWithKey:nil];
        } else {
            [self.dataService loadDataWithKey:self.searchView.textField.text];
        }
    }
    if (direction == MSRefreshDirectionBottom || _fastSearch) {
        if (self.searchView.textField.text == 0) {
            [self.dataService loadMoreDataWithKey:nil];
        } else {
            [self.dataService loadMoreDataWithKey:self.searchView.textField.text];
        }
    }
}

@end
